using System.Linq;
using MvcContrib.Pagination;
using NHibernate.SqlCommand;
using NHibernate.Transform;
using OTE.Web.Mvc.Areas.Admin.Controllers.ViewModels;
using SharpArch.NHibernate;

namespace OTE.Web.Mvc.Areas.Admin.Controllers.Queries.Category
{
    /// <summary>
    /// http://stackoverflow.com/questions/4977038/can-i-use-nhibernate-criteria-to-project-an-entity-and-its-child-collection-onto
    /// </summary>
    public class CategoryListQuery : NHibernateQuery, ICategoryListQuery
    {
        public IPagination<CategoryViewModel> GetPagedList(int page, int size)
        {
            Domain.Category categoryAlias = null;
            Domain.CategoryContent categoryContentAlias = null;

            var query = Session.QueryOver(() => categoryAlias);// Session.QueryOver<Domain.Category>();

            var count = query.ToRowCountQuery();
            var totalCount = count.FutureValue<int>();

            var firstResult = (page - 1) * size;

            var viewModels = query
                                    .JoinAlias(() => categoryAlias.CategoryContents, () => categoryContentAlias, JoinType.LeftOuterJoin)
                                    .TransformUsing(Transformers.DistinctRootEntity)
                                    .List<Domain.Category>()
                                    .Select(x => new CategoryViewModel
                                    {
                                        Id = x.Id,
                                        CategoryContents = x.CategoryContents.Select(
                                            content => new CategoryContentViewModel
                                                        {
                                                            Id = content.Id,
                                                            Name = content.Name,
                                                            CreatedBy = content.CreatedBy,
                                                            CreatedDate = content.CreatedDate,
                                                            ModifiedBy = content.ModifiedBy,
                                                            ModifiedDate = content.ModifiedDate
                                                        }).ToArray()
                                    })
                                    .Skip(firstResult)
                                    .Take(size)
                                    .ToArray();

            return new CustomPagination<CategoryViewModel>(viewModels, page, size, totalCount.Value);
        }
    }
}